package firebase

import (
	"cat_mouse/infra/utils/log"
	"encoding/json"
	"fmt"
	"github.com/kirinlabs/HttpRequest"
	"github.com/pkg/errors"
	"net/http"
	"sync"
)

type RespDto struct {
	IdToken      string
	RefreshToken string
	ExpiresIn    int
}

type Firebase struct {
}

func (f *Firebase) AuthApiKey(apiKey string) (string, error) {
	var (
		token string
		req   *HttpRequest.Request
		resp  *HttpRequest.Response
		err   error
	)
	url := fmt.Sprintf("https://securetoken.googleapis.com/v1/token?key=[%s]", apiKey)
	headers := map[string]string{"Content-Type": "application/x-www-form-urlencoded"}
	req = HttpRequest.NewRequest().SetTimeout(3).SetHeaders(headers)
	if resp, err = req.Post(url); err != nil {
		log.Logger.Error(err)
		return token, err
	}
	if resp.StatusCode() != http.StatusOK {
		log.Logger.Error(err)
		return token, errors.New("Invalid response")
	}
	respDto := RespDto{}
	bs, _ := resp.Body()
	if err = json.Unmarshal(bs, &respDto); err != nil {
		log.Logger.Errorf("%s |%s", err.Error(), string(bs))
		return token, err
	}
	return token, err
}

var (
	fireBaseIns  *Firebase
	fireBaseOnce sync.Once
)

func NewFirebase() *Firebase {
	fireBaseOnce.Do(func() {
		fireBaseIns = &Firebase{}
	})
	return fireBaseIns
}
